package com.jagochan.imchat.module.common.utils.redissonlock;

import com.jagochan.imchat.module.common.exception.BusinessException;
import com.jagochan.imchat.module.common.exception.CommonErrorEnum;
import lombok.SneakyThrows;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

@Component
public class RedissonLockService {

    @Resource
    private RedissonClient redissonClient;


    @SneakyThrows
    public <T> T executeWithLockThrows(String key, long waitTime, TimeUnit timeUnit, SupplierThrow<T> supplier) {
        RLock lock = redissonClient.getLock(key);
        boolean success = lock.tryLock(waitTime, timeUnit);
        if (!success) {
            throw new BusinessException(CommonErrorEnum.LOCK_LIMIT);
        }
        try {
            return supplier.get();
        } finally {
            lock.unlock();
        }
    }

    @FunctionalInterface
    public interface SupplierThrow<T> {
        T get() throws Throwable;
    }

}
